import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

;(function () {
  const scripts = document.getElementsByTagName('script')
  let appKey, server_ip
  for (let i = scripts.length - 1; i >= 0; i--) {
    const script = scripts[i]
    if (script.getAttribute('status') == 'chat-widget') {
      console.log(script.src)
      appKey = script.getAttribute('data-appkey')
      if (script.getAttribute('src').split('/media')[0]) {
        server_ip = script.getAttribute('src').split('/media')[0]
      } else {
        server_ip = 'http://127.0.0.1:8888'
      }
      break
    }
  }

  if (!appKey) {
    console.error('未提供 APPKEY，请在 script 标签中添加 data-appkey 属性')
    return
  }

  // 监听 beforeunload 事件
  window.addEventListener('beforeunload', () => {
    const chatHistoryId = localStorage.getItem('chat_history_id')
    if (chatHistoryId) {
      localStorage.removeItem('chat_history_id')
    }
  })

  localStorage.setItem('chatWidgetAppKey', appKey)
  localStorage.setItem('server_ip', server_ip)

  const container = document.createElement('div')
  container.id = 'chat-widget-container'
  // 设置容器样式，确保不影响页面布局
  container.style.position = 'fixed'
  container.style.zIndex = '9999'
  container.style.right = '0'
  container.style.bottom = '0'
  container.style.width = 'auto'
  container.style.height = 'auto'
  container.style.overflow = 'visible'

  document.body.appendChild(container)

  const chatWidgetApp = createApp(App)
  const pinia = createPinia() // 创建 Pinia 实例
  chatWidgetApp.use(pinia) // 使用 Pinia
  chatWidgetApp.config.globalProperties.$appKey = appKey
  chatWidgetApp.mount('#chat-widget-container')
})()
